let currentCategory = '';
let currentType = '';

// 当页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
    const categoryBoxes = document.querySelectorAll('.category-box');
    categoryBoxes.forEach(box => {
        box.addEventListener('click', () => {
            const category = box.getAttribute('data-category');
            loadQuestions(category);
        });
    });
});

// 加载题目分类
function loadQuestions(category) {
    currentCategory = category;
    document.getElementById('category-title').textContent = category;
    const questionTypes = document.getElementById('question-types');
    questionTypes.innerHTML = `
                <div class="type-options">
                    <button onclick="loadQuestionList('${category}', 'reading')">阅读理解</button>
                    <button onclick="loadQuestionList('${category}', 'writing')">写作</button>
                    <button onclick="loadQuestionList('${category}', 'translation')">翻译</button>
                    <button class="add-question-btn" onclick="showQuestionForm()">添加新题目</button>
                </div>
            `;
}

// 加载题目列表
function loadQuestionList(category, type) {
    currentCategory = category;
    currentType = type;

    document.getElementById('question-list').innerHTML = `
                <div id="loading">正在加载题目...</div>
                <div class="question-items"></div>
            `;

    axios.get(`/api/questions?category=${category}&type=${type}`)
        .then(response => {
            const questionItems = document.querySelector('.question-items');
            questionItems.innerHTML = '';

            if(response.data.length === 0) {
                questionItems.innerHTML = '<p>暂无题目，请添加新题目。</p>';
                return;
            }

            response.data.forEach(question => {
                const questionDiv = document.createElement('div');
                questionDiv.className = 'question-item';
                questionDiv.innerHTML = `
                        <div class="question-content">${question.content}</div>
                        <div class="question-answer">答案: ${question.answer}</div>
                        <div class="question-analysis">解析: ${question.analysis || '无'}</div>
                        <div class="question-difficulty">难度: ${question.difficulty || '未设置'}</div>
                        <div class="question-actions">
                            <button onclick="editQuestion('${question.id}')">编辑</button>
                            <button class="delete-btn" onclick="deleteQuestion('${question.id}')">删除</button>
                        </div>
                    `;
                questionItems.appendChild(questionDiv);
            });

            document.getElementById('loading').style.display = 'none';
        })
        .catch(error => {
            console.error('加载题目出错:', error);
            alert('加载题目出错: ' + (error.response?.data?.message || error.message));
        });
}

// 显示题目表单（添加新题目）
function showQuestionForm() {
    document.getElementById('question-form-content').reset();
    document.getElementById('question-id').value = '';
    document.getElementById('question-form').classList.remove('hidden');
}

// 编辑题目
function editQuestion(questionId) {
    axios.get(`/api/questions/${questionId}`)
        .then(response => {
            const question = response.data;
            document.getElementById('content').value = question.content;
            document.getElementById('answer').value = question.answer;
            document.getElementById('analysis').value = question.analysis || '';
            document.getElementById('difficulty').value = question.difficulty || '';
            document.getElementById('question-id').value = questionId;

            document.getElementById('question-form').classList.remove('hidden');
        })
        .catch(error => {
            console.error('加载题目出错:', error);
            alert('加载题目出错: ' + (error.response?.data?.message || error.message));
        });
}

// 提交题目表单
function submitQuestion() {
    const questionId = document.getElementById('question-id').value;
    const content = document.getElementById('content').value;
    const answer = document.getElementById('answer').value;
    const analysis = document.getElementById('analysis').value;
    const difficulty = document.getElementById('difficulty').value;


    if (!difficulty || difficulty < 1 || difficulty > 5) {
        alert('请输入1-5的难度值');
        return;
    }
    if (!content || !answer) {
        alert('请填写所有必填字段');
        return;
    }

    const questionData = {
        content: content,
        answer: answer,
        analysis: analysis,
        difficulty: difficulty,
        category: currentCategory,
        type: currentType
    };

    if (questionId) {
        // 修改现有题目
        axios.put(`/api/questions/${questionId}`, questionData)
            .then(()=> {
                alert('题目修改成功！');
                closeForm();
                loadQuestionList(currentCategory, currentType);
            })
            .catch(error => {
                console.error('修改题目出错:', error);
                alert('修改题目出错: ' + (error.response?.data?.message || error.message));
            });
    } else {
        // 添加新题目
        axios.post('/api/questions', questionData)
            .then(() => {
                alert('题目添加成功！');
                closeForm();
                loadQuestionList(currentCategory, currentType);
            })
            .catch(error => {
                console.error('添加题目出错:', error);
                alert('添加题目出错: ' + (error.response?.data?.message || error.message));
            });
    }
}

// 删除题目
function deleteQuestion(questionId) {
    if(!confirm('确定要删除这个题目吗？')) {
        return;
    }

    axios.delete(`/api/questions/${questionId}`)
        .then(response => {
            alert('题目删除成功!');
            loadQuestionList(currentCategory, currentType);
        })
        .catch(error => {
            console.error('删除题目出错:', error);
            alert('删除题目出错: ' + (error.response?.data?.message || error.message));
        });
}

// 关闭题目表单
function closeForm() {
    document.getElementById('question-form').classList.add('hidden');
}